package com.sample.library.util

import android.R
import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.hjq.bar.initializer.CommonBarInitializer.getDrawableResources
import com.sample.library.ClickProxy
import com.sample.library.ext.ProxyClickListener
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.*

object ViewUtil {

    fun download(activity: Activity, view: View, fileName: String): String {

        val metric = DisplayMetrics()
        activity.windowManager.defaultDisplay.getMetrics(metric)
        val width = metric.widthPixels / 4 * 3 // 屏幕宽度（像素）
        val height = metric.heightPixels // 屏幕高度（像素）
        layoutView(view, width, height) //去到指定view大小的函数
        val shareBitmap = loadBitmapFromView(view)
        val myCaptureFile = File(activity.filesDir.absolutePath + File.separator + fileName + ".jpg")
        if (myCaptureFile.exists()) {
            myCaptureFile.delete()
        }
        val bos: BufferedOutputStream
        try {
            bos = BufferedOutputStream(FileOutputStream(myCaptureFile))
            shareBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos)
            bos.flush()
            bos.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return myCaptureFile.absolutePath
    }

    fun downloadDICM(activity: Activity, view: View, fileName: String) {
        val metric = DisplayMetrics()
        activity.windowManager.defaultDisplay.getMetrics(metric)
        val width = metric.widthPixels / 4 * 3 // 屏幕宽度（像素）
        val height = metric.heightPixels // 屏幕高度（像素）
        layoutView(view, width, height) //去到指定view大小的函数
        val shareBitmap = loadBitmapFromView(view)
        BitmapUtil.saveBitmap(view.context, shareBitmap, "$fileName.jpg")
    }

    //然后View和其内部的子View都具有了实际大小，也就是完成了布局，相当与添加到了界面上。接着就可以创建位图并在上面绘制了：
    private fun layoutView(v: View, width: Int, height: Int) {
        // 指定整个View的大小 参数是左上角 和右下角的坐标
        v.layout(0, 0, width, height)
        val measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY)
        val measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST)
        /** 当然，measure完后，并不会实际改变View的尺寸，需要调用View.layout方法去进行布局。
         * 按示例调用layout函数后，View的大小将会变成你想要设置成的大小。
         */
        v.measure(measuredWidth, measuredHeight)
        v.layout(0, 0, v.measuredWidth, v.measuredHeight)
    }

    private fun loadBitmapFromView(v: View): Bitmap {
        val w = v.width
        val h = v.height
        val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
        val c = Canvas(bmp)
        c.drawColor(Color.WHITE)
        /** 如果不设置canvas画布为白色，则生成透明  */
        v.layout(0, 0, w, h)
        v.draw(c)
        return bmp
    }

    fun getAllChildViews(view: View?): List<View> {
        val allchildren: MutableList<View> = ArrayList()
        if (view is ViewGroup) {
            for (i in 0 until view.childCount) {
                val viewchild = view.getChildAt(i)
                allchildren.add(viewchild)
                //再次 调用本身（递归）
                allchildren.addAll(getAllChildViews(viewchild))
            }
        }
        return allchildren
    }

    /**
     * 获取水波纹的点击效果
     */
    /**
     * 获取水波纹的点击效果
     */
    fun getRippleDrawable(context: Context): Drawable? {
        val typedValue = TypedValue()
        return if (context.theme.resolveAttribute(R.attr.selectableItemBackground, typedValue, true)) {
            getDrawableResources(context, typedValue.resourceId)
        } else null
    }

    //防止重复点击
    fun View.setOnProxyClickListener(listener: ProxyClickListener) {
        this.setOnClickListener(ClickProxy {
            listener.invoke(it)
        })
    }

    /**
     * 获取十六进制的颜色代码.例如  "#5A6677"
     * 分别取R、G、B的随机值，然后加起来即可
     *
     * @return String
     */
    fun getRandColor(): String? {
        var R: String
        var G: String
        var B: String
        val random = Random()
        R = Integer.toHexString(random.nextInt(256)).toUpperCase()
        G = Integer.toHexString(random.nextInt(256)).toUpperCase()
        B = Integer.toHexString(random.nextInt(256)).toUpperCase()
        R = if (R.length == 1) "0$R" else R
        G = if (G.length == 1) "0$G" else G
        B = if (B.length == 1) "0$B" else B
        return "#$R$G$B"
    }

    fun isLightColor(color: Int): Boolean {
        val darkness = 1 - (0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color)) / 255
        return darkness < 0.4
    }

    fun isLightColor2(color: Int): Boolean {
        val darkness = 1 - (0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color)) / 255
        return darkness < 0.1
    }

    fun getLightColor(): String? {
        var c = getRandColor()
        if (!isLightColor2(Color.parseColor(c))) {
            c = getLightColor()
        }
        return c
    }

    //获取深色
    fun getDarkColor(): String? {
        var c = getRandColor()
        if (isLightColor(Color.parseColor(c))) {
            c = getDarkColor()
        }
        return c
    }

    fun setViewpager2(viewpager2: ViewPager2?) {
        try {
            val recyclerViewField = ViewPager2::class.java.getDeclaredField("mRecyclerView")
            recyclerViewField.isAccessible = true
            val recyclerView = recyclerViewField[viewpager2] as RecyclerView
            val touchSlopField = RecyclerView::class.java.getDeclaredField("mTouchSlop")
            touchSlopField.isAccessible = true
            val touchSlop = touchSlopField[recyclerView] as Int
            touchSlopField[recyclerView] = touchSlop * 2 //6 is empirical value
        } catch (ignore: Exception) {
        }
    }
}